﻿using System;
using System.IO;
using System.Windows.Forms;

namespace AtletIS.Shared.Helpers
{
    public class WordHelper
    {
        public static void CreateWordFromHtml(string htmlFilePath)
        {
            try
            {
                Type wordType = Type.GetTypeFromProgID("Word.Application");

                dynamic wordApp = Activator.CreateInstance(wordType);

                wordApp.Visible = false;
                wordApp.ScreenUpdating = false;

                FileInfo inputFile = new FileInfo(htmlFilePath);

                try
                {
                    object fileFormat = 0; // 0 = word document
                    object saveChanges = 0; // 0 = do not save pending changes

                    string inputFileName = inputFile.FullName.ToString();
                    string outputFileName = inputFile.FullName.Replace(".html", ".doc");

                    var doc = wordApp.Documents.Open(ref inputFileName);

                    doc.PageSetup.TopMargin = 36;
                    doc.PageSetup.BottomMargin = 36;
                    doc.PageSetup.LeftMargin = 36;
                    doc.PageSetup.RightMargin = 36;

                    doc.SaveAs2(ref outputFileName, ref fileFormat);
                    doc.Close(ref saveChanges);

                    doc = null;

                    wordApp.Quit();

                    File.Delete(htmlFilePath);  // delete HTML file, because WORD file is opened

                    System.Diagnostics.Process.Start(outputFileName);
                }
                catch
                {
                    if (wordApp != null)
                        wordApp.Quit();

                    System.Diagnostics.Process.Start(htmlFilePath);
                }
            }
            catch
            {
                System.Diagnostics.Process.Start(htmlFilePath);
            }
        }

    }
}
